//
//  SmallDecisionsSlViewController.m
//  SmallDecisions
//
//  Created by 李付雄 on 2025/8/7.
//

#import "SmallDecisionsSlViewController.h"
#import "SmallDecisionsSlCell.h"
#import "SmallDecisionsSlModel.h"
#import "SmallDecisionsSlResultViewController.h"

@interface SmallDecisionsSlViewController ()<UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSArray *leiList;
@property (nonatomic, strong) NSMutableArray *slList;
@property (nonatomic, strong) UILabel *leiTotalLabel;
@property (nonatomic, strong) UIImageView *bombAnimationImageView;
@property (nonatomic, assign) NSInteger bombNumber;
@property (nonatomic, assign) BOOL isAnimation;

@end

@implementation SmallDecisionsSlViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    [self collectionView];
}

#pragma mark UICollectionViewDelegate,UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.slList.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SmallDecisionsSlCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SmallDecisionsSlCellId" forIndexPath:indexPath];
    SmallDecisionsSlModel *slModel = self.slList[indexPath.item];
    cell.imageView.image = [UIImage imageNamed:slModel.defaultImageName];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if(!self.isAnimation) {
        self.isAnimation = YES;
        SmallDecisionsSlCell *cell = (SmallDecisionsSlCell *)[collectionView cellForItemAtIndexPath:indexPath];
        SmallDecisionsSlModel *slModel = self.slList[indexPath.item];
        @weakify(self);
        if(!slModel.isFinish) {
            if(slModel.isLei) {
                self.bombNumber -= 1;
                self.leiTotalLabel.text = [NSString stringWithFormat:@"剩余雷数:%ld",(long)self.bombNumber];
                cell.imageView.image = [UIImage imageNamed:slModel.leiImageName];
                self.bombAnimationImageView.hidden = NO;
                [self.bombAnimationImageView startAnimating];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    weak_self.bombAnimationImageView.hidden = YES;
                    SmallDecisionsSlResultViewController *slResultVC = [[SmallDecisionsSlResultViewController alloc] init];
                    slResultVC.allEnd = weak_self.bombNumber == 0 ? NO : weak_self.allEnd;
                    slResultVC.callback = ^(NSDictionary *dic) {
                        if([dic[@"refresh"] boolValue]) {
                            [weak_self setDefaultListWithTotal:self.slList.count];
                            [weak_self.collectionView reloadData];
                        }
                        weak_self.isAnimation = NO;
                    };
                    [SmallDecisionsNavigatorManager presentViewController:slResultVC showNavigationBar:NO animationType:SmallDecisionsAnimationTypeAlert];
                });
                
                slModel.isLei = YES;
            } else {
                cell.imageView.image = [UIImage imageNamed:slModel.safeImageName];
                self.isAnimation = NO;
            }
            slModel.isFinish = YES;
        } else {
            self.isAnimation = NO;
        }
    }
    
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        CGFloat itemWH = (self.view.width - 10 * 6 ) / 5.0;
        layout.itemSize = CGSizeMake(itemWH, itemWH);
        layout.sectionInset = UIEdgeInsetsMake(5, 10, 5, 10);
        layout.minimumInteritemSpacing = 10;
        layout.minimumLineSpacing = [self getRowSpacingWithCellHeight:itemWH]; // cell 间距
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.alwaysBounceVertical = YES;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [self.view addSubview:_collectionView];
        [_collectionView registerClass:[SmallDecisionsSlCell class] forCellWithReuseIdentifier:@"SmallDecisionsSlCellId"];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_offset(10);
            make.left.right.top.mas_offset(0);
            make.bottom.mas_offset(-self.view.safeAreaInsets.bottom);
        }];
    }

    return _collectionView;
}

- (NSMutableArray *)slList {
    if(!_slList) {
        _slList = [[NSMutableArray alloc] init];
    }
    return _slList;
}

- (CGFloat)getRowSpacingWithCellHeight:(CGFloat)cellH {
    CGFloat containerHeight = kScreenHeight - 10 - NavBarHeight - self.view.safeAreaInsets.bottom;
    NSInteger rowNum = floor(containerHeight / cellH);
    CGFloat spacing = (containerHeight - (rowNum * cellH)) / (rowNum - 1);
    [self setDefaultListWithTotal:rowNum * 5];
    return spacing;
}

- (void)setDefaultListWithTotal:(NSInteger)total {
    [self.slList removeAllObjects];
    
    // 不允许重复的情况
    NSMutableSet *uniqueNumbers = [NSMutableSet set];
    while (uniqueNumbers.count < self.slTotal) {
        NSInteger randomNum = arc4random_uniform((uint32_t)(total));
        [uniqueNumbers addObject:@(randomNum)];
    }
    // 设置雷
    NSInteger unique = 0;
    while (self.slList.count < total) {
        NSDictionary *dic = @{
            @"defaultImageName":@"sl_default_img",
            @"safeImageName":@"sl_safe_img",
            @"leiImageName":@"sl_bomb_img",
            @"isFinish":@(NO),
            @"isLei":@([uniqueNumbers containsObject:@(unique)])
        };
        unique += 1;
        SmallDecisionsSlModel *slModel = [SmallDecisionsSlModel yy_modelWithJSON:dic];
        [self.slList addObject:slModel];
    }
    
    self.bombNumber = self.slTotal;
    self.leiTotalLabel.text = [NSString stringWithFormat:@"剩余雷数:%ld",(long)self.slTotal];
}


- (UIImageView *)bombAnimationImageView {
    if(!_bombAnimationImageView) {
        // 创建硬币图像视图
        _bombAnimationImageView = [[UIImageView alloc] init];
        _bombAnimationImageView.image = [UIImage imageNamed:@"bomb_animation_img_0"]; // 默认显示正面
        _bombAnimationImageView.contentMode = UIViewContentModeScaleAspectFit;
        [self.view addSubview:_bombAnimationImageView];
        _bombAnimationImageView.animationImages = @[[UIImage imageNamed:@"bomb_animation_img_0"], [UIImage imageNamed:@"bomb_animation_img_1"],[UIImage imageNamed:@"bomb_animation_img_2"],[UIImage imageNamed:@"bomb_animation_img_3"],[UIImage imageNamed:@"bomb_animation_img_4"],[UIImage imageNamed:@"bomb_animation_img_5"],[UIImage imageNamed:@"bomb_animation_img_6"],[UIImage imageNamed:@"bomb_animation_img_7"],[UIImage imageNamed:@"bomb_animation_img_8"],[UIImage imageNamed:@"bomb_animation_img_9"]];
        _bombAnimationImageView.animationDuration = 1.5;
        _bombAnimationImageView.animationRepeatCount = 1;
        [_bombAnimationImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.mas_equalTo(0);
            make.width.height.mas_equalTo(200);
        }];
        _bombAnimationImageView.hidden = YES;
    }
    return _bombAnimationImageView;
}

- (UIView *)setCenterBarView {
    UIView *centerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    centerView.backgroundColor = SmallDecisionsSecondBgColor;
    centerView.layer.cornerRadius = 22;
    centerView.layer.masksToBounds = YES;
    UILabel *leiTotalLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
    leiTotalLabel.textColor = SmallDecisionsThemeFontColor;
    leiTotalLabel.font = SmallDecisionsSetFontSize(16);
    leiTotalLabel.textAlignment = 1;
    [centerView addSubview:leiTotalLabel];
    self.leiTotalLabel = leiTotalLabel;
    return centerView;
}

- (void)backBarButtonAction:(UIView *)view {
    [SmallDecisionsAlertViewController showAlertWithTitle:nil message:@"确定退出该游戏吗？" cancelText:@"取消" otherText:@"确定" dismissCompletion:^(SMALL_DECISIONS_PROJECT_ALERT_HANDLE_EVENTS event) {
        if(event == SMALL_DECISIONS_PROJECT_ALERT_HANDLE_EVENTS_OTHER) {
            [SmallDecisionsNavigatorManager popViewControllerAnimated:YES];
        }
    }];
}

@end
